package convert;

import java.util.ArrayList;

import main.Def;

import org.apache.poi.ss.usermodel.Cell;
import org.jdom.Element;

import config.EConfig;

public class EColumn extends BaseContent
{
	private ESheet m_sheet;
	
	public EColumn(ESheet sheet, String name, ERow father)
	{
		super(name, father);
		m_sheet = sheet;
	}
	
	public void init(Head head)
	{
		int end = ((ERow)m_father).getEnd();
		for(int i = ((ERow)m_father).getStart(); i <= end;)
		{
			int min = end - i + 10;
			ArrayList<MergeCell> merges = new ArrayList<>();
			for(int c = head.getStart(); c <= head.getEnd(); ++c)
			{
				MergeCell mc = m_sheet.isMergeCell(i, c);
				merges.add(mc);
				int h = 1;
				if(mc != null)
				{
					h = mc.getHeight();
					c = mc.getX2();
				}
				if(h < min)
				{
					min = h;
				}
			}
			int index = 0;
			Cell[] cells = new Cell[merges.size()];
			for(int c = head.getStart(); c <= head.getEnd(); ++c, ++index)
			{
				int row = i;
				int col = c;
				MergeCell mc = merges.get(index);
				if(mc != null)
				{
					c = mc.getX2();
					row = mc.getY1();
					col = mc.getX1();
				}
				cells[index] = m_sheet.getCellAt(row, col);
			}
			addChild(new ECell(cells, this));
			i += min;
		}
	}
	
	public void toXml(Element node)
	{
		Element col = null;
		if(EConfig.m_isSimpleFormat)
		{
			col = new Element(m_name);
		}
		else
		{
			col = new Element(Def.COLUMN);
			col.setAttribute(Def.NAME, m_name);
		}
		if(m_children != null)
		{
			for(BaseContent bc: m_children)
			{
				if(bc.m_name.length() != 0)
				{
					Element temp = null;
					if(EConfig.m_isSimpleFormat)
					{
						temp = new Element(bc.m_name);
					}
					else
					{
						temp = new Element(Def.CELL);
						temp.setAttribute(Def.NAME, bc.m_name);
					}
					col.addContent(temp);
				}
			}
		}
		node.addContent(col);
	}
	/*
	public void fromXml(XmlNode node, int column) throws ErrorException
	{
		ERow rc = (ERow)m_father;
		for(int i = 0, size = node.getChildNumber(); i < size; ++i)
		{
			XmlNode temp = node.getChild(i);
			String name = temp.getAttribute(Def.VALUE);
			m_sheet.setValue(column, rc.getStart() + i, name);
		}
	}*/
}
